<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class SourceCount extends Model
{
    protected $fillable = [
        'ip','source_id'
    ];

    public function setIpAttribute($value)
    {
        $this->attributes['ip'] = ip2long($value);
    }

    public function getIpAttribute($value)
    {
        return long2ip($value);
    }

    /**
     * Description:通过时间点来获取数据
     * Author: liuju
     * DateTime: 2019-03-06 17:14
     * @param $query
     * @param $date
     * @param $hour
     * @return mixed
     */
    public function  scopeGetDataByDateHour($query, $date,$hour)
    {
        return $query->whereDate('created_at','=',$date)
            ->whereTime('created_at','>=',$hour.':00')
            ->whereTime('created_at','<=',$hour.':59');
    }


    /**
     * Description:获取某渠道数据
     * Author: liuju
     * DateTime: 2019-03-06 18:29
     * @param $query
     * @param $source
     *  @return mixed
     */
    public function  scopeGetDataBySource($query, $source)
    {
        return $query->where('source_id',$source);
    }

    /**
     * Description: 获取pv来源，从而判断是否有pv数据
     * Author: liuju
     * DateTime: 2019-03-07 19:28
     * @param $date
     * @param $hour
     * @return mixed
     */
    public static function getPvSource($date,$hour)
    {
        return self::whereDate('created_at',$date)
            ->whereTime('created_at','>=',$hour.':00')
            ->whereTime('created_at','<=',$hour.':59')
            ->groupBy('ip')
            ->pluck('source_id')->toArray();
    }


    /**
     * Description: 获取PV数据
     * Author: liuju
     * DateTime: 2019-03-07 19:35
     * @param $source
     * @param $date
     * @param $hour
     * @return mixed
     */
    public static function getPvData($date,$hour,$source)
    {
        $data =  self::getDataByDateHour($date, $hour)
            ->getDataBySource($source)
            ->value(DB::raw('count(id)'));
        return $data ? $data :0;
    }

    /**
     * Description:获取用户uv数据
     * Author: liuju
     * DateTime: 2019-03-07 19:35
     * @param $source
     * @param $date
     * @param $hour
     * @return mixed
     */
    public static function getUvData($date,$hour,$source)
    {
        $data =  self::getDataByDateHour($date, $hour)
            ->getDataBySource($source)
            ->groupBy('ip')
            ->pluck('ip');
        return $data ? count($data) : 0;
    }
}
